import { AddDepartmentBean, DepartmentItem, UpdateDepartmentBean } from './data';
import { useRef, useState } from 'react';
import { addDepartment, deleteDepartment, queryDepartment, updateDepartment } from './service';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Button, Divider, Modal, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import AddForm from './components/AddForm';
import { SUCCESS_CODE } from '@/utils/request';
import UpdateForm from './components/UpdateForm';
import ViewPosition from './components/ViewPosition';
import { useModel } from 'umi';

export default () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser?.permissions;
  const {
    'ADMIN.DEPARTMENT.ADD': add,
    'ADMIN.DEPARTMENT.UPDATE': update,
    'ADMIN.DEPARTMENT.DELETE': Delete,
  } = currUser;

  const [departmentId, setDepartmentId] = useState<string>();
  const [departmentData, setDepartmentData] = useState<DepartmentItem>();
  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [viewPositionVisible, setViewPositionVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  function convertData(data: { id: any; pid: any; name: any; next_level: string | any[] }) {
    const node = {
      id: data.id,
      pid: data.pid,
      name: data.name,
      children: [] as any,
    };
    if (data.next_level && data.next_level.length > 0) {
      for (let i = 0; i < data.next_level.length; i++) {
        const child = convertData(data.next_level[i]);
        node.children.push(child);
      }
    }
    return node;
  }

  const addDepartmentEvent = async (values: AddDepartmentBean) => {
    const res = await addDepartment(values);
    if (res.code === SUCCESS_CODE) {
      message.success('添加成功');
      handleAddModalVisible(false);
      actionRef.current?.reload();
    } else {
      message.error(res.message || '添加失败');
    }
  };

  const updateDepartmentEvent = async (values: UpdateDepartmentBean) => {
    const res = await updateDepartment(values);
    if (res.code === SUCCESS_CODE) {
      message.success('修改成功');
      handleUpdateModalVisible(false);
      actionRef.current?.reload();
    } else {
      message.error(res.message || '修改失败');
    }
  };

  const columns: ProColumns<DepartmentItem>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '部门名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '操作',
      dataIndex: 'options',
      render: (_, record) => {
        const onClickRemove = () => {
          const { id, name } = record;
          Modal.confirm({
            title: `删除部门 ${id}`,
            content: (
              <>
                <Divider />
                <p>确认要删除部门</p>
                <span style={{ fontWeight: 'bolder' }}>{name}</span>
                &nbsp;&nbsp;?
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await deleteDepartment(id);
              actionRef.current?.reload();
            },
            centered: true,
            width: '30vw',
            style: { height: '15vw' },
          });
        };
        return (
          <>
            <a
              onClick={() => {
                setDepartmentData(record);
                setViewPositionVisible(true);
              }}
            >
              查看职位
            </a>
            {add && (
              <>
                <Divider type="vertical" />
                <a
                  onClick={() => {
                    setDepartmentId(record.id);
                    handleAddModalVisible(true);
                  }}
                >
                  添加子部门
                </a>
              </>
            )}
            {update && (
              <>
                <Divider type="vertical" />

                <a
                  onClick={() => {
                    setDepartmentData(record);
                    handleUpdateModalVisible(true);
                  }}
                >
                  编辑
                </a>
              </>
            )}
            {Delete && (
              <>
                <Divider type="vertical" />
                <a onClick={onClickRemove}>删除</a>
              </>
            )}
          </>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<DepartmentItem>
        pagination={{
          defaultPageSize: 10,
          size: 'default',
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        search={false}
        headerTitle="部门列表"
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: true }}
        toolBarRender={() => [
          <>
            {add && (
              <Button
                key={''}
                type="primary"
                onClick={() => {
                  setDepartmentId('1');
                  handleAddModalVisible(true);
                }}
              >
                <PlusOutlined /> 添加
              </Button>
            )}
          </>,
        ]}
        tableAlertRender={() => false}
        rowSelection={false}
        request={async () => {
          const res = await queryDepartment();
          const result: DepartmentItem[] = [];
          if (res && res.code == 0) {
            const data = res?.data;
            if (data && data.length > 0) {
              for (let i = 0; i < data.length; i++) {
                result.push(convertData(data[i]));
              }
            }
          }
          res.data = result;

          return res;
        }}
        columns={columns}
      />
      {addModalVisible && departmentId && (
        <AddForm
          pid={departmentId}
          onSubmit={addDepartmentEvent}
          onCancel={() => handleAddModalVisible(false)}
          modalVisible={addModalVisible}
          visibleHandler={() => handleAddModalVisible(false)}
        />
      )}
      {updateModalVisible && departmentData && (
        <UpdateForm
          department={departmentData}
          onSubmit={updateDepartmentEvent}
          onCancel={() => handleUpdateModalVisible(false)}
          modalVisible={updateModalVisible}
          visibleHandler={() => handleUpdateModalVisible(false)}
        />
      )}
      {viewPositionVisible && departmentData && (
        <ViewPosition
          department={departmentData}
          visible={viewPositionVisible}
          onClose={() => setViewPositionVisible(false)}
        />
      )}
    </PageHeaderWrapper>
  );
};
